package com.exm.collectcodenew.activemq.consumer;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

public class ActiveMQQueueMsListenerConsumer {
    public static final String ACTIVEMQ_URL ="tcp://59.110.35.177:61616";
    public static final String QUEUE_NAME ="queue01";

    public static void main(String[] args) throws JMSException, IOException {
        //1.连接工厂，采用给定的url地址，采用默认的用户名密码
        ActiveMQConnectionFactory activeMQConnectionFactory =new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂创建连接，并启动
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();
        //3.创建会话session
        //两个参数，第一个叫事务/第二个叫签收
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //4.创建目的地（队列/topic）
        Queue queue = session.createQueue(QUEUE_NAME);
        //5.创建消费者
        MessageConsumer consumer = session.createConsumer(queue);
        //6.通过监听的方式来消费消息
        consumer.setMessageListener((message)->{
            if(null!=message && message instanceof  TextMessage){
                TextMessage textMessage = (TextMessage)message;
                try {
                    System.out.println("*****消费者接收到消息："+textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        System.in.read();//接受键盘输入，按下Enter键结束输入，保持控制台不灭
        //7.关闭资源
        consumer.close();
        session.close();
        connection.close();
        System.out.println("****消息消费完成****");    }

}
